package com.wave.wavesystem.business.interceptor;

import com.wave.wavesystem.business.pojo.entity.UserEntity;
import com.wave.wavesystem.common.util.AuthUtil;
import com.wave.wavesystem.common.util.Func;
import com.wave.wavesystem.common.util.ThrowUtil;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import wave.common.pojo.entity.BaseEntity;
import wave.common.pojo.enums.RStatusEnum;

import java.sql.Connection;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class InsertSqlInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
            StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
            String sql = statementHandler.getBoundSql().getSql().toUpperCase();
            if (!sql.startsWith("INSERT")) {
                return invocation.proceed();
            }
            Map<String, Object> inserMap = (Map<String, Object>) statementHandler.getBoundSql().getParameterObject();
            inserMap.forEach((k, v) -> {
                if (v instanceof BaseEntity) {
                    UserEntity currentUser = AuthUtil.getUser();
                    ThrowUtil.throwIf(Func.isEmpty(currentUser), RStatusEnum.AUTH_FAIL);
                    ((BaseEntity) v).setCreateUser(currentUser.getId());
                }
            });
            System.out.println("SQL: " + sql);
            return invocation.proceed();

    }

}